// Copyright 2010 Alexandre Tristan St-Cyr <tristan.stcyr@gmail.com>

package com.codeplex.loadjava;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.jar.JarFile;

class ClassPathReader {
	
	final String[] paths;
	
	public ClassPathReader(String classpath)
	{
		this.paths = classpath.split(";");
	}
	
	public void accept(IClassPathVisitor visitor)
	{
		for(String path : paths)
		{
			File file = new File(path);
			if (file.isDirectory()) {
				for(File subfile : file.listFiles()) {
					this.visitClassFiles(visitor, subfile, "");
				}
			} else {
				String extension = PathHelper.getExtension(file.getName());
				if (extension.equals("jar")) {
					JarFile jarFile= null;
					try {
						try {
							jarFile = new JarFile(file);
							JarFileReader jarFileReader = new JarFileReader(jarFile);
							jarFileReader.accept(visitor);
						} finally {
							if (jarFile != null)
								jarFile.close();
						}
					} catch(IOException e) {
						visitor.onError(e);
					}
				} else if (extension.equals("class")) {
					this.visitClassFiles(visitor, file, "");
				}
			} 
		}
	}

	private void visitClassFiles(IClassPathVisitor visitor, File file, String relativePath)
	{
		if (file.isFile()) {
			String extension = PathHelper.getExtension(file.getName());
			if (extension != null)
			{
				try {
					if (extension.equals("class"))
					{
						FileInputStream inputStream = null;
						try {
							inputStream = new FileInputStream(file);
							visitor.visit(inputStream, relativePath+file.getName());
						} finally {
							if (inputStream != null) {
								inputStream.close();
							}
						}
					}
				} catch(IOException e) {
					visitor.onError(e);
				} 
			}
		} else if (file.isDirectory()) {
			String newRelativePath = relativePath + file.getName() + "/";
			for(File subfile : file.listFiles()) {
				this.visitClassFiles(visitor, subfile, newRelativePath);
			}
		}
	}
}
